package pers.chao.tool.thread;

import java.util.HashMap;
import java.util.Map;
import java.util.function.Supplier;

/**
 * Description: threadLocal工具
 *
 * @author W.Chao
 * @date 2020/11/8 15:58
 **/
public final class ThreadLocalUtil {
	private static final ThreadLocal<Map<String, Object>> LOCAL = ThreadLocal.withInitial(HashMap::new);

	private ThreadLocalUtil() {
	}

	public static Map<String, Object> getAll() {
		return LOCAL.get();
	}

	public static <T> T put(String key, T value) {
		LOCAL.get().put(key, value);
		return value;
	}

	public static void remove(String key) {
		LOCAL.get().remove(key);
	}

	public static void clear() {
		LOCAL.remove();
	}

	@SuppressWarnings("unchecked")
	public static <T> T get(String key) {
		return ((T) LOCAL.get().get(key));
	}

	/**
	 * 从ThreadLocal中获取值，并指定一个当值不存在的默认提供者
	 * e.g
	 * ThreadLocal.get("key", new Object())
	 *
	 * @param key
	 * @param supplierOnNull
	 * @param <T>
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T> T get(String key, Supplier<T> supplierOnNull) {
		return ((T) LOCAL.get().computeIfAbsent(key, k -> supplierOnNull.get()));
	}

	public static <T> T getAndRemove(String key) {
		try {
			return get(key);
		} finally {
			remove(key);
		}
	}
}
